package com.zxlfysj.greedy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

/**
 * 贪心算法实例
 *
 * @author yangshujing
 * @create 2020-08-25 23:08
 */
public class GreedyAlgorithm {
    public static void main(String[] args) {
        //实现使用最少广播电台覆盖地区
        HashMap<String, HashSet<String>> broadcasts = new HashMap<>();
        //电台1
        HashSet<String> hashSet1 = new HashSet<>();
        hashSet1.add("北京");
        hashSet1.add("上海");
        hashSet1.add("天津");
        //电台2
        HashSet<String> hashSet2 = new HashSet<>();
        hashSet2.add("广州");
        hashSet2.add("北京");
        hashSet2.add("深圳");
        //电台3
        HashSet<String> hashSet3 = new HashSet<>();
        hashSet3.add("成都");
        hashSet3.add("上海");
        hashSet3.add("杭州");
        //电台4
        HashSet<String> hashSet4 = new HashSet<>();
        hashSet4.add("上海");
        hashSet4.add("天津");
        //电台5
        HashSet<String> hashSet5 = new HashSet<>();
        hashSet5.add("大连");
        hashSet5.add("杭州");
        //加入map
        broadcasts.put("K1", hashSet1);
        broadcasts.put("K2", hashSet2);
        broadcasts.put("K3", hashSet3);
        broadcasts.put("K4", hashSet4);
        broadcasts.put("K5", hashSet5);

        //存放所有地区的hashset
        HashSet<String> allAreas = new HashSet<>();
        allAreas.add("北京");
        allAreas.add("上海");
        allAreas.add("天津");
        allAreas.add("广州");
        allAreas.add("深圳");
        allAreas.add("成都");
        allAreas.add("杭州");
        allAreas.add("大连");
        //存放选择的电台集合
        ArrayList<String> selects = new ArrayList<>();
        //每次取出电台临时存放
        HashSet<String> tempSet = new HashSet<>();

        String maxKey = null;
        int maxSize = 0;

        while (allAreas.size() != 0) {
            maxKey = null;
            maxSize = 0;
            for (String key : broadcasts.keySet()) {
                tempSet.clear();
                HashSet<String> areas = broadcasts.get(key);
                tempSet.addAll(areas);
                tempSet.retainAll(allAreas);
                //每次选择最优的
                if (tempSet.size() > 0 && (maxKey == null || tempSet.size() > maxSize)) {
                    maxKey = key;
                    maxSize = tempSet.size();
                }
            }
            if (maxKey != null) {
                selects.add(maxKey);
                allAreas.removeAll(broadcasts.get(maxKey));  //移除已经覆盖电台的城市
            }
        }
        System.out.println(selects);


    }
}
